/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.UserHotProject;
import com.alien.admin.modules.deploy.service.DpServerService;
import com.alien.admin.modules.deploy.service.dto.DpServerDto;
import com.alien.admin.utils.ValidationUtil;
import com.alien.admin.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.UserHotProjectRepository;
import com.alien.admin.modules.deploy.service.UserHotProjectService;
import com.alien.admin.modules.deploy.service.dto.UserHotProjectDto;
import com.alien.admin.modules.deploy.service.dto.UserHotProjectQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.UserHotProjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.alien.admin.utils.PageUtil;
import com.alien.admin.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-12-13
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class UserHotProjectServiceImpl implements UserHotProjectService {

    private final UserHotProjectRepository userHotProjectRepository;
    private final UserHotProjectMapper userHotProjectMapper;
    private final DpServerService dpServerService;

    @Override
    public Map<String, Object> queryAll(UserHotProjectQueryCriteria criteria, Pageable pageable) {
        Page<UserHotProject> page = userHotProjectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(userHotProjectMapper::toDto));
    }

    @Override
    public List<UserHotProjectDto> queryAll(UserHotProjectQueryCriteria criteria) {
        return userHotProjectMapper.toDto(userHotProjectRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public List<UserHotProjectDto> findByUserId(Long userId) {

        List<UserHotProjectDto> userHotProjectDtoList = userHotProjectMapper.toDto(userHotProjectRepository.findByUserIdOrderByUpdateTimeDesc(userId));
        if (!CollectionUtils.isEmpty(userHotProjectDtoList)) {
            for (UserHotProjectDto dto : userHotProjectDtoList) {
                DpServerDto dpServerDto = dpServerService.findById(dto.getProjectId());
                if (dpServerDto == null) {
                    log.info("dpServerDto is null. projectId:{}", dto.getProjectId());
                    continue;
                }
                dto.setProjectName(dpServerDto.getName());
            }
        }
        return userHotProjectDtoList;
    }

    @Override
    @Transactional
    public UserHotProjectDto findById(Integer id) {
        UserHotProject userHotProject = userHotProjectRepository.findById(id).orElseGet(UserHotProject::new);
        ValidationUtil.isNull(userHotProject.getId(), "UserHotProject", "id", id);
        return userHotProjectMapper.toDto(userHotProject);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserHotProjectDto create(UserHotProject resources) {
        return userHotProjectMapper.toDto(userHotProjectRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserHotProjectDto createOrUpdate(UserHotProject resources) {
        Integer id = userHotProjectRepository.getByUerIdAndProjectIdAndEnv(resources.getUserId(), resources.getProjectId(), resources.getEnv());
        if (id == null) {
            return create(resources);
        } else {
            Optional<UserHotProject> userHotProjectOpt = userHotProjectRepository.findById(id);
            userHotProjectOpt.get().setUpdateTime(resources.getUpdateTime());
            return userHotProjectMapper.toDto(userHotProjectRepository.save(userHotProjectOpt.get()));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserHotProject resources) {
        UserHotProject userHotProject = userHotProjectRepository.findById(resources.getId()).orElseGet(UserHotProject::new);
        ValidationUtil.isNull(userHotProject.getId(), "UserHotProject", "id", resources.getId());
        userHotProject.copy(resources);
        userHotProjectRepository.save(userHotProject);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            userHotProjectRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<UserHotProjectDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserHotProjectDto userHotProject : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户", userHotProject.getUserId());
            map.put("环境", userHotProject.getEnv());
            map.put("项目id", userHotProject.getProjectId());
            map.put("创建日期", userHotProject.getCreateTime());
            map.put("更新时间", userHotProject.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
